package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存阅读行为
     * 1.阅读行为不需要回显和查询,所以不需要保存到redis,直接保存到数据库即可
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {

        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadUtil.getUser();
        if (user == null && dto.getEquipmentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.查询用户阅读行为
        Criteria criteria = new Criteria().orOperator(Criteria.where("userID").is(user.getId()), Criteria.where("equipmentId").is(dto.getEquipmentId())).andOperator(Criteria.where("articleId").is(dto.getArticleId()));

        ApReadBehavior apReadBehavior=mongoTemplate.findOne(Query.query(criteria),ApReadBehavior.class);

        //文章不是第一次被阅读
        if(apReadBehavior!=null){
            apReadBehavior.setCount(apReadBehavior.getCount()+1);
            apReadBehavior.setUpdatedTime(new Date());
            apReadBehavior.setReadDuration(dto.getReadDuration());
            mongoTemplate.save(apReadBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //文章第一次被阅读
        apReadBehavior=new ApReadBehavior();
        apReadBehavior.setReadDuration(dto.getReadDuration());
        apReadBehavior.setUpdatedTime(new Date());
        apReadBehavior.setArticleId(dto.getArticleId());
        apReadBehavior.setCount(1);
        apReadBehavior.setCreatedTime(new Date());
        apReadBehavior.setLoadDuration(dto.getLoadDuration());
        apReadBehavior.setUserId(user.getId().longValue());
        apReadBehavior.setEquipmentId(dto.getEquipmentId());

        mongoTemplate.insert(apReadBehavior);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
